package gateway02.handler;

import cn.hutool.json.JSONUtil;
import common05.common.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.*;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * 全局异常处理类
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Results results = null;

        if (ex instanceof MethodNotAllowedException) {
            results = Results.method_not_allowed();
        }

        if (ex instanceof NotFoundException) {
            results = Results.service_unavailable();
        }

        if (ex instanceof ResponseStatusException) {
            results = Results.not_found();
        }

        if (ex instanceof UnsupportedMediaTypeStatusException) {
            results = Results.unsupported_media_type();
        }

        if (results == null) {
            results = Results.error();
        }

        DataBuffer buffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(results).getBytes(Charset.forName("UTF-8")));
        log.error(ex.getMessage(), ex);
        return response.writeWith(Mono.just(buffer));
    }
}
